﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Kalman.Extensions;
using Kalman;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json.Linq;

namespace QuDao.Api.Controllers
{
    /// <summary>
    /// 行政区划API
    /// </summary>
    [AllowAnonymous]
    public class AreaController : ApiControllerBase
    {
        IMapper _mapper = null;
        public AreaController(IMapper mapper)
        {
            _mapper = mapper;
        }

        /// <summary>
        /// 获取开通服务的区域列表（城市及区县）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<AreaDto> GetServiceArea()
        {
            var list = AreaBO.Instance.GetServiceArea();
            return list;
        }

        /// <summary>
        /// 获取省份列表
        /// </summary>
        [HttpGet]
        public IEnumerable<AreaDto> GetProvinceList()
        {
            var list = AreaBO.Instance.GetListByLevel(1);
            return _mapper.Map<IEnumerable<AreaDto>>(list);
        }

        /// <summary>
        /// 获取省份信息
        /// </summary>
        /// <param name="areaID">区域ID（省市县ID都可以）</param>
        /// <returns></returns>
        [HttpGet]
        public Area GetProvince(int areaID)
        {
            if (areaID < 100000 || areaID > 999999) return null;
            var provinceID = int.Parse($"{areaID.ToString()[..2]}0000");
            return AreaBO.Instance.GetProvince(provinceID);
        }

        /// <summary>
        /// 获取省份信息
        /// </summary>
        /// <param name="provinceName">省份名称</param>
        /// <returns></returns>
        [HttpGet]
        public Area GetProvinceByName(string provinceName)
        {
            return AreaBO.Instance.GetProvince(provinceName);
        }

        /// <summary>
        /// 获取城市列表
        /// </summary>
        /// <param name="province">省份ID或省份名称，传空或不传取全部城市数据</param>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<AreaDto> GetCityList(string province = "")
        {
            var list = Enumerable.Empty<Area>();
            if (province.IsNullOrWhiteSpace())
            {
                list = AreaBO.Instance.GetListByLevel(2);
            }
            else
            {
                if (char.IsDigit(province[0]))
                {
                    if (int.TryParse(province, out int id))
                    {
                        list = AreaBO.Instance.GetCityList(id);
                    }
                }
                else
                {
                    list = AreaBO.Instance.GetCityList(province);
                }
            }

            return _mapper.Map<IEnumerable<AreaDto>>(list);
        }

        /// <summary>
        /// 获取县级区域列表
        /// </summary>
        /// <param name="city">城市ID或城市名称</param>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<AreaDto> GetCountyList(string city)
        {
            if (city.IsNullOrWhiteSpace()) throw new AppException("城市ID或城市名称不能为空");

            var list = Enumerable.Empty<Area>();
            if (char.IsDigit(city[0]))
            {
                if (int.TryParse(city, out int id))
                {
                    list = AreaBO.Instance.GetCountyList(id);
                }
            }
            else
            {
                list = AreaBO.Instance.GetCountyList(city);
            }

            return _mapper.Map<IEnumerable<AreaDto>>(list);
        }

        /// <summary>
        /// 根据当前地理位置定位所在城市
        /// </summary>
        /// <param name="lng">地理经度</param>
        /// <param name="lat">地理纬度</param>
        /// <returns></returns>
        [HttpGet]
        public CityDto GetLocationCity(decimal lng, decimal lat)
        {
            var districtID = AmapUtil.GetDistrictID(lng, lat);
            var district = AreaBO.Instance.GetArea(districtID);
            var city = AreaBO.Instance.GetCity(330100);//杭州
            
            if (district == null)
            {
                district = AreaBO.Instance.GetArea(330199);//钱塘县
            }
            else
            {
                city = AreaBO.Instance.GetCity(district.ParentID);
            }

            var dto = new CityDto
            {
                ProvinceID = city.ParentID,
                CityID = city.AreaID,
                CityName = city.AreaName,
                CityShortName = city.ShortName,
                CountyID = district.AreaID,
                CountyName = district.AreaName,
                CountyShortName = district.ShortName
            };

            dto.CountyList = AreaBO.Instance.GetCountyList(dto.CityID);
            return dto;
        }

        /// <summary>
        /// 获取当前地理位置信息（高德地图API调用）
        /// </summary>
        /// <param name="lng">地理经度</param>
        /// <param name="lat">地理纬度</param>
        /// <returns></returns>
        [HttpGet]
        public JObject GetAmapLocation(decimal lng, decimal lat)
        {
            return AmapUtil.GetLocation(lng, lat);
        }

        /// <summary>
        /// 重置区域数据缓存
        /// </summary>
        [HttpGet]
        public void Reload()
        {
            AreaBO.Instance.Reload();
        }

        //[HttpPost]
        //public PagingResult<Area> Query([FromBody] PagingRequest req)
        //{
        //    var result = AreaBO.Instance.Query<Area>(req);
        //    return result;
        //}


    }
}
